package com.zrwl.poscloud.commons.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 文件下载工具类
 *
 * @ClassName: FileDownloadUtil
 * @Description: 文件下载工具类
 */
@Slf4j
public class FileDownloadUtil {


    /**
     * 以流的方式下载
     * @param directoryName
     * @param response
     * @return
     */
    public static HttpServletResponse download(String directoryName, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(directoryName);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(".".lastIndexOf(filename) + 1).toUpperCase();
            // 以流的形式下载文件。
            byte[] buffer;
            try (InputStream fis = new BufferedInputStream(Files.newInputStream(Paths.get(directoryName)))) {
                buffer = new byte[fis.available()];
                fis.read(buffer);
            }
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            log.error(ex.getMessage());
        }
        return response;
    }
    public void downLoadIsOnLine(String fileName, HttpServletRequest request, HttpServletResponse response, boolean isOnLine) throws IOException {
        String absolutePath = fileName;
        File f = new File(absolutePath);
        if (!f.exists()) {
            response.sendError(404, "文件未找到!");
            return;
        }
        //解决中文乱码
        String userAgent = request.getHeader("user-agent").toLowerCase();
        fileName = f.getName();
        String downloadFileName;

        if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
            downloadFileName = URLEncoder.encode((fileName), "UTF-8");
        } else {
            downloadFileName = new String((fileName).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        byte[] buf = new byte[1024];
        int len = 0;

        response.reset(); // 非常重要
        // 在线打开方式
        if (isOnLine) {
            URL u = new URL("file:///" + absolutePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + downloadFileName);
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + downloadFileName);
        }
        try (BufferedInputStream br = new BufferedInputStream(Files.newInputStream(f.toPath())); OutputStream out = response.getOutputStream()) {
            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
    }
}

